package com.dhecp.project.api.controller;

import com.alibaba.fastjson.JSON;
import com.dhecp.common.utils.StringUtils;
import com.dhecp.core.utils.DateUtils;
import com.dhecp.project.api.domain.ApiResponse;
import com.dhecp.project.api.service.ApiAmazonService;
import com.dhecp.project.api.service.ApiLogService;
import com.dhecp.project.api.util.ApiConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Map;

/**
 * @ClassName ApiAmazonController
 * @Description TODO
 * @Author alula
 * @Date 2022-10-12 16:48
 */
@Controller
@RequestMapping("/api/amazon")
public class ApiAmazonController {
    private static final Logger logger = LoggerFactory.getLogger(ApiAmazonController.class);

    //亚马逊系统名称
    private static final String AMAZON_SYSTEM_NAME = "Amazon";

    @Autowired
    private ApiLogService apiLogService;

    @Autowired
    private ApiAmazonService apiAmazonService;

    /**
     * 获取某用户明细运营公司对应的店铺订单数据
     * @param params 格式为{"shopGuids":"店铺表guid，多个用逗号隔开","userId":"0000"}
     * @return
     */
    @RequestMapping("/getAmazonOrderInfo")
    @ResponseBody
    public ApiResponse getAllAmazonOrderInfo(@RequestParam(required = true) Map<String, Object> params) throws Exception
    {
        ApiResponse apiResponse = new ApiResponse();
        if (!params.containsKey("paymentTime")){
            apiResponse.setSuccess(false);
            apiResponse.setMessage("参数执行时间不存在!");
            apiResponse.setCode(0);
            return  apiResponse;
        }
//        String userId = (String) params.get("userId");
//        if (StringUtils.isEmpty(userId)){
//            apiResponse.setSuccess(false);
//            apiResponse.setMessage("参数userId不能为空!");
//            apiResponse.setCode(0);
//            return  apiResponse;
//        }
//        String shopGuids = (String) params.get("shopGuids");
//        if (StringUtils.isEmpty(shopGuids)){
//            apiResponse.setSuccess(false);
//            apiResponse.setMessage("参数shopGuids不能为空!");
//            apiResponse.setCode(0);
//            return  apiResponse;
//        }
//        String[] dataIds = shopGuids.split(",");
//        params.put("dataIds", dataIds);
//        //admin用户直接移除userId，参数
//        if (userId.equals("admin")){
//            params.remove("userId");
//        }
        params.put("authorizeState","已授权");
        int insertLogId = 0;
        String type = "GetAmazonOrderInfo";
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        //传入的时间
        Date startTime = DateUtils.firstAndLateData(-1,0,0,0,0,0,1,dateFormat.parse(String.valueOf(params.get("paymentTime"))));
        Date endTime = DateUtils.firstAndLateData(0,0,59,59,23,23,0,null);//当天23：59:59
        try {
            insertLogId = apiLogService.addApiLog(AMAZON_SYSTEM_NAME,type,"dataParams：" + params,"",0, "");
            apiResponse = apiAmazonService.getAllAmazonOrderInfo(insertLogId, AMAZON_SYSTEM_NAME, type, params, startTime,1,endTime);
            if (apiResponse.getCode() == 500){
                apiLogService.updateApiLog(insertLogId, AMAZON_SYSTEM_NAME, type, "dataParams：" + params, "ECP_API手动调用获取亚马逊店铺订单信息接口出错，错误为："+apiResponse.getMessage(), apiResponse.getCode(), apiResponse.getMessage());
            }
        }
        catch (Exception ex) {
            apiResponse.setCode(500);
            apiResponse.setMessage("ECP_API手动调用获取亚马逊店铺订单信息接口出错，错误为" + ex.getMessage());
        }
        return apiResponse;
    }

    /**
     * 获取指定亚马逝店铺产品信息
     * @param params 格式为{"prodGuids":"店铺产品表guid，多个用逗号隔开","userId":"0000"}
     * @return
     */
    @RequestMapping("/getAmazonShopProductInfo")
    @ResponseBody
    public ApiResponse getAmazonShopProductInfo(@RequestParam(required = true) Map<String, Object> params)
    {
        ApiResponse apiResponse = new ApiResponse();
        if (!params.containsKey("userId")){
            apiResponse.setSuccess(false);
            apiResponse.setMessage("参数userId不存在!");
            apiResponse.setCode(0);
            return  apiResponse;
        }
        String userId = (String) params.get("userId");
        if (StringUtils.isEmpty(userId)){
            apiResponse.setSuccess(false);
            apiResponse.setMessage("参数userId不能为空!");
            apiResponse.setCode(0);
            return  apiResponse;
        }
        if (!params.containsKey("prodGuids")){
            apiResponse.setSuccess(false);
            apiResponse.setMessage("参数prodGuids不存在!");
            apiResponse.setCode(0);
            return  apiResponse;
        }
        String prodGuids = (String) params.get("prodGuids");
        if (StringUtils.isEmpty(prodGuids)){
            apiResponse.setSuccess(false);
            apiResponse.setMessage("参数prodGuids不能为空!");
            apiResponse.setCode(0);
            return  apiResponse;
        }
        String[] dataIds = prodGuids.split(",");
        params.put("dataIds", dataIds);
        int insertLogId = 0;
        String type = "GetAmazonShopProductInfo";
        try {
            insertLogId = apiLogService.addApiLog(AMAZON_SYSTEM_NAME,type,"dataParams：" + params,"",0, "");
            apiResponse = apiAmazonService.getAllAmazonShopProductInfo(insertLogId, AMAZON_SYSTEM_NAME, type, params);
            if (apiResponse.getCode() == 500){
                apiLogService.updateApiLog(insertLogId, AMAZON_SYSTEM_NAME, type, "dataParams：" + params, "ECP_API手动调用获取亚马逊店铺产品信息接口出错，错误为："+apiResponse.getMessage(), apiResponse.getCode(), apiResponse.getMessage());
            }
        }
        catch (Exception ex) {
            apiResponse.setCode(500);
            apiResponse.setMessage("ECP_API手动调用获取亚马逊店铺产品信息接口出错，错误为" + ex.getMessage());
        }
        return apiResponse;
    }

    /**
     * 获取亚马逊授权URL地址
     * @param params params 格式为{"shopId":"店铺guid","userId":"0000"}
     * @return
     */
    @RequestMapping("/getAmazonAuthUrl")
    @ResponseBody
    public ApiResponse getAmazonAuthUrl(@RequestParam(required = true) Map<String, Object> params)
    {
        ApiResponse apiResponse = apiAmazonService.getAmazonAuthUrl(params);
        return apiResponse;
    }

    /**
     * 亚马逊授权回调地址
     * @param params
     * @param response
     */
    @RequestMapping("/amazonAuthCallback")
    public void amazonAuthCallBack(@RequestParam(required = true) Map<String, Object> params, HttpServletResponse response) throws IOException {

        int insertLogId = 0;
        String type = "GetAmazonToken";
        try {
            System.out.println("amazon授权回调参数：" + JSON.toJSONString(params));
            String code = (String) params.get("spapi_oauth_code");
            String state = (String) params.get("state");
            String sellingId = (String) params.get("selling_partner_id");
            insertLogId = apiLogService.addApiLog(AMAZON_SYSTEM_NAME,type,"dataParams：" + params,"",0, "");
            ApiResponse apiResponse = apiAmazonService.getAmazonToken(insertLogId, AMAZON_SYSTEM_NAME, type, code, state);
            if (apiResponse.getCode() == 500){
                apiLogService.updateApiLog(insertLogId, AMAZON_SYSTEM_NAME, type, "dataParams：" + params, "ECP_API获取亚马逊授权TOKEN出错，错误为："+apiResponse.getMessage(), apiResponse.getCode(), apiResponse.getMessage());
            }
            if (apiResponse.getSuccess() == true) {
                response.sendRedirect(ApiConfig.getApiDeployUrl() + "/api/amazon/amazontokenauth?auth=yes");
            } else {
                response.sendRedirect(ApiConfig.getApiDeployUrl() + "/api/amazon/amazontokenauth?auth=no");
            }
        }
        catch (Exception ex) {
            response.sendRedirect(ApiConfig.getApiDeployUrl() + "/api/amazon/amazontokenauth?auth=no");
        }
    }

    /**
     * 获取亚马逊广告授权URL地址
     * @param params params 格式为{"shopId":"店铺guid","userId":"0000"}
     * @return
     */
    @RequestMapping("/getAmazonAuthUrlGg")
    @ResponseBody
    public ApiResponse getAmazonAuthUrlGg(@RequestParam(required = true) Map<String, Object> params)
    {
        ApiResponse apiResponse = apiAmazonService.getAmazonAuthUrlGg(params);
        return apiResponse;
    }

    /**
     * 亚马逊授权广告回调地址
     * @param params
     * @param response
     */
    @RequestMapping("/amazonAuthCallbackGg")
    public void amazonAuthCallBackGg(@RequestParam(required = true) Map<String, Object> params, HttpServletResponse response) throws IOException {

        int insertLogId = 0;
        String type = "GetAmazonGgToken";
        try {
            System.out.println("amazon授权回调参数：" + JSON.toJSONString(params));
            String code = (String) params.get("code");
            String state = (String) params.get("state");
            insertLogId = apiLogService.addApiLog(AMAZON_SYSTEM_NAME,type,"dataParams：" + params,"",0, "");
            ApiResponse apiResponse = apiAmazonService.getAmazonTokenGg(insertLogId, AMAZON_SYSTEM_NAME, type, code, state);
            if (apiResponse.getCode() == 500){
                apiLogService.updateApiLog(insertLogId, AMAZON_SYSTEM_NAME, type, "dataParams：" + params, "ECP_API获取亚马逊授权广告TOKEN出错，错误为："+apiResponse.getMessage(), apiResponse.getCode(), apiResponse.getMessage());
            }
            if (apiResponse.getSuccess() == true) {
                response.sendRedirect(ApiConfig.getApiDeployUrl() + "/api/amazon/amazontokenauth?auth=yes");
            } else {
                response.sendRedirect(ApiConfig.getApiDeployUrl() + "/api/amazon/amazontokenauth?auth=no");
            }
        }
        catch (Exception ex) {
            response.sendRedirect(ApiConfig.getApiDeployUrl() + "/api/amazon/amazontokenauth?auth=no");
        }
    }


    /**
     * 亚马逊token回调显示页面
     * @return
     */
    @RequestMapping("/amazontokenauth")
    public  String amazonTokenAuth(@RequestParam(required = true) String auth, ModelMap mmap){
        if (StringUtils.isEmpty(auth)){
            auth = "no";
        }
        String message = "";
        if (auth.contains("yes")){
            message = "亚马逊店铺授权成功!";
        }else{
            message = "亚马逊店铺授权失败!";
        }
        mmap.put("message", message);
        return "error/amazontokenauth";
    }
}
